package com.s2.m.btchat;

import java.util.Enumeration;
import javax.microedition.lcdui.Command;
import javax.microedition.lcdui.CommandListener;
import javax.microedition.lcdui.Display;
import javax.microedition.lcdui.Displayable;
import javax.microedition.lcdui.Form;
import javax.microedition.lcdui.List;

/**
 * Shows the <code>ChatScreen</code>s currently active. The user can select
 * one from the list. And the corresponding <code>ChatScreen</code> is opened.
 * @author Samik Saha
 */
public class ActiveChats implements CommandListener {
    /**
     * Reference to the current midlet's display
     */
    Display display;
    /**
     * List to display the names of friends currently active in chay
     */
    List list = new List("Chats", List.IMPLICIT);
    /**
     * Command to go back to the previous screen
     */
    private Command backCommand = new Command("Back", Command.BACK, 0);
    /**
     * Keeps a reference to the displayble previously being displayed
     */
    private Displayable prevDisplayable;

    /**
     * Creates a <code>ActiveChats</code> instance. Shows the list of active
     * <code>ChatScreen</code>s. If no <code>ChatScreen</code> is active then
     * an appropriate message is displayed in a Form.
     */
    public ActiveChats() {
        display = Display.getDisplay(BTChat.getInstance());
        prevDisplayable = display.getCurrent();
        if (!ChatScreen.activeChats.isEmpty()) {
            Enumeration e = ChatScreen.activeChats.keys();
            while (e.hasMoreElements()) {
                list.append((String) e.nextElement(), null);
            }
            list.addCommand(backCommand);
            list.setCommandListener(this);
            display.setCurrent(list);
        }else{
            Form status = new Form("Chats");
            status.append("No Active Chats");
            status.addCommand(backCommand);
            status.setCommandListener(this);
            display.setCurrent(status);
        }
    }

    /**
     * Implementation of the <code>commandAction</code> method of the
     * <code>CommandListener</code> interface
     * @param c the <code>Command</code> Object
     * @param d the <code>Displayable</code> Object
     */
    public void commandAction(Command c, Displayable d) {
        if (c == List.SELECT_COMMAND) {
            String name = list.getString(list.getSelectedIndex());
            ChatScreen chatScreen = (ChatScreen) ChatScreen.activeChats.get(name);
            chatScreen.showUI();
        } else if (c == backCommand) {
            display.setCurrent(prevDisplayable);
        }
    }
}
